<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert type="warning" title="注意：只允许为第三级设置分类参数" :closable="false" show-icon></el-alert>
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader v-model="selectKes" :options="cateList" :props="cateProps" @change="handleChange"
                        clearable>
                    </el-cascader>
                </el-col>
            </el-row>

            <!-- tab -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数
                    </el-button>
                    <el-table :data="manyTableData" border stripe>
                        <el-table-column type="expand" label="展开">
                            <template slot-scope="scope">
                                <el-tag v-for="(item, idx) in scope.row.attr_vals" :key="idx" closable
                                    @close="handleClose(idx,scope.row)">{{item}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">新建标签
                                </el-button>


                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="序号☺️">序号</el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="small" icon="el-icon-edit"
                                    @click="showEditDialog(scope.row.attr_id)">编辑
                                </el-button>
                                <el-button type="danger" size="small" icon="el-icon-delete"
                                    @click="delParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性
                    </el-button>
                    <el-table :data="onlyTableData" border stripe>
                        <el-table-column type="expand" label="展开">
                            <template slot-scope="scope">
                                <el-tag v-for="(item, idx) in scope.row.attr_vals" :key="idx" closable
                                    @close="handleClose(idx,scope.row)">{{item}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">新建标签
                                </el-button>


                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="序号☺️">序号</el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="small" icon="el-icon-edit"
                                    @click="showEditDialog(scope.row.attr_id)">编辑
                                </el-button>
                                <el-button type="danger" size="small" icon="el-icon-delete"
                                    @click="delParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-dialog :title="'添加' + addTitleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">

            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="addTitleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>

            </el-form>


            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="'修改' + addTitleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">

            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="addTitleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>

            </el-form>


            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>


<script>
    export default {
        data() {
            return {
                cateList: [],
                selectKes: [],
                cateProps: {
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children'
                },
                activeName: 'many',
                manyTableData: [],
                onlyTableData: [],
                addDialogVisible: false,
                editDialogVisible: false,
                addForm: {
                    attr_name: ''
                },
                addFormRules: {
                    attr_name: [
                        { required: true, message: "请输入参数", trigger: 'blur' },
                        { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
                    ]
                },
                editForm: {
                    attr_name: ''
                }

            }
        },
        created() {
            this.getCateList()
        },
        methods: {
            async getCateList() {
                const { data: res } = await this.$http.get('categories')
                if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
                this.cateList = res.data
            },

            async handleChange() {
                this.getParamsData()

            },
            handleTabClick() {
                this.getParamsData()

            },
            async getParamsData() {
                if (this.selectKes.length !== 3) { //非三级分类
                    this.selectKes = []
                    this.manyTableData = []
                    this.onlyTableData = []
                    return
                }
                //获取分类id获取对应面板参数数据
                const { data: res } = await this.$http.get(`categories/${this.catedId}/attributes`, { params: { sel: this.activeName } }
                )
                if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')

                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
                    //文本框显示与隐藏，绑定各自的身上，防止复用
                    item.inputVisible = false
                    item.inputValue = ''
                });
                console.log(res.data);

                if (this.activeName === 'many') {
                    this.manyTableData = res.data;
                } else {
                    this.onlyTableData = res.data;
                }
            },
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            addParams() {
                this.$refs.addFormRef.validate(async vd => {
                    if (!vd) return
                    const { data: res } = await this.$http.post(`categories/${this.catedId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
                    if (res.meta.status !== 201) return this.$message.error('添加失败')
                    this.$message.success('添加成功')
                    this.addDialogVisible = false
                    this.getParamsData()
                })
            },
            async showEditDialog(attr_id) {
                const { data: res } = await this.$http.get(`categories/${this.catedId}/attributes/${attr_id}`, { params: { attr_sel: this.activeName } })
                if (res.meta.status !== 200) return this.$message.error('获取参数失败')
                this.editForm = res.data
                this.editDialogVisible = true

            },
            editParams() {
                this.$refs.editFormRef.validate(async vd => {
                    if (!vd) return
                    const { data: res } = await this.$http.put(`categories/${this.catedId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
                    if (res.meta.status !== 200) return this.$message.error('修改参数失败')
                    this.$message.success('修改参数成功')
                    this.getParamsData()
                    this.editDialogVisible = false
                })
            },
            editDialogClosed() {
                this.$refs.editFormRef.resetFields()
            },

            async delParams(attr_id) {
                const cfmRst = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)

                if (cfmRst !== "confirm") {
                    return this.$message.info('已取消删除')
                }
                const { data: res } = await this.$http.delete(`categories/${this.catedId}/attributes/${attr_id}`)
                if (res.meta.status !== 200) return this.$message.error('删除失败')
                this.$message.success('删除成功')
                this.getParamsData()
            },

            //文本框回车或失去焦点
            async handleInputConfirm(rowData) {
                let v = rowData.inputValue.trim()
                if (v.length === 0) {
                    rowData.inputValue = ''
                    rowData.inputVisible = false
                    return
                }
                rowData.attr_vals.push(v)
                rowData.inputValue = ''
                rowData.inputVisible = false

                this.saveAttrVals(rowData)
            },


            async saveAttrVals(rowData) {
                const { data: res } = await this.$http.put(`categories/${this.catedId}/attributes/${rowData.attr_id}`, {
                    attr_name: rowData.attr_name,
                    attr_sel: rowData.attr_sel,
                    attr_vals: rowData.attr_vals.join(' ')
                })
                if (res.meta.status !== 200) return this.$message.error('修改参数失败')
                this.$message.success('修改参数成功')
            },

            showInput(rowData) {
                rowData.inputVisible = true
                //$nextTick 作用：页面重新渲染后，再回调
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },

            //删除参数
            handleClose(idx, rowData) {
                rowData.attr_vals.splice(idx, 1)
                this.saveAttrVals(rowData)
            }


        },
        computed: {
            isBtnDisabled() {
                return this.selectKes.length !== 3
            },
            catedId() {
                return this.selectKes.length === 3 ? this.selectKes[2] : null;
            },
            addTitleText() {
                return this.activeName === 'many' ? "动态参数" : "静态属性"
            }
        }
    }
</script>

<style lang="less" scoped>
    .cat_opt {
        margin: 15px 0;
    }

    .el-tag {
        margin: 10px;
    }

    .input-new-tag {
        width: 100px;
    }
</style>